import MainCard from '@/ui-component/cards/MainCard'
import { DatePeriod } from '@/types/common'
import { getSalaryAdvisorList } from '@/api'
import { DefaultPagination, PageSizes, gridSpacing } from '@/store/constant'
import useColumns from './useColumns'
import { GridRowsProp } from '@mui/x-data-grid-pro'
import PeriodSelector from '../performance/PeriodSelector'

const Index = () => {
  const theme = useTheme()
  const matches = useMediaQuery(theme.breakpoints.up('md'))
  const [paginationModel, setPaginationModel] = useState(DefaultPagination)
  const [params, setParams] = useState<DatePeriod>({
    start_date: '',
    end_date: ''
  })

  const { data, refresh, loading } = useRequest(
    () => getSalaryAdvisorList({ page: paginationModel.page + 1, size: paginationModel.pageSize, ...params }),
    {
      manual: true,
      cacheKey: `/salary/total/history?page=${paginationModel.page}`,
      refreshDeps: [params, paginationModel],
      debounceWait: 500,
      onSuccess(res) {
        setRows(res?.data ?? [])
      }
    }
  )

  const [rows, setRows] = useState<GridRowsProp>([])
  const columns = useColumns({ refresh })

  useEffect(() => {
    if (!isEmpty(params.start_date)) {
      refresh()
    }
  }, [params, paginationModel])

  return (
    <MainCard
      title={
        <Grid container spacing={1} alignItems="center">
          <Grid item xs={9} sm={6} md={3}>
            <PeriodSelector period={params} setPeriod={setParams} />
          </Grid>
          <Grid item xs={3} sm={6} md={3}>
            <LoadingButton loading={loading} variant="contained" color="secondary" onClick={refresh}>
              Search
            </LoadingButton>
          </Grid>
        </Grid>
      }
    >
      <Grid container spacing={gridSpacing}>
        <Grid item xs={12} sx={{ minHeight: 500 }}>
          <DataGridPro
            rows={rows}
            columns={columns}
            pageSizeOptions={PageSizes}
            editMode="cell"
            pagination
            paginationModel={paginationModel}
            onPaginationModelChange={setPaginationModel}
            rowCount={data?.total ?? DefaultPagination.pageSize}
            disableRowSelectionOnClick
            paginationMode="server"
            {...(matches && { pinnedColumns: { left: ['name_grade', 'status'], right: ['actions'] } })}
          />
        </Grid>
      </Grid>
    </MainCard>
  )
}

export default Index
